package com.yfdice.android.bam;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*; 
import android.widget.AdapterView.*;
import android.content.*;
import android.util.*;

import java.util.*;

import com.yfdice.android.bam.MoniterService.MoniterItem;

import android.view.*;
//import android.app.*;
import android.graphics.Color;
import android.os.*;

//TODO 4。设置对话，先加音量调整
public class BurglarAlarmMonitor extends Activity  implements OnClickListener, IMainOperation {
	
	private static final String TAG = "bamactivity";
	
	private DisplayMetrics metrics;
	private ListView m_listView;
	private ListView m_searchView;
	private ListAdapter m_listItemAdapter;
	private SearchAdapter m_searchlistAdapter;
	
	private FrameLayout mMonitorlist_up;
	private FrameLayout mMonitorlist_middle;
	private LinearLayout mMonitorlist_down;
	
	private FrameLayout mSearchlist_up;
	private FrameLayout mSearchlist_middle;
	private LinearLayout mSearchlist_down;
	
	private int mPosition = 0;
	private int mFilterType = DeviceItem.FilterType_None;
	
	public final class RSSIValue {
		public int nMaxRSSI; 
		public String strDescription;
		public int nResId;
	}
	private ArrayList<RSSIValue> m_RSSIValues = new ArrayList<RSSIValue>();
 
	//dialog which show operation
	private static final int DIALOG_OPERATE = 3;
	private static final int DIALOG_QUIT = 2;
	private static final int DIALOG_DELETE = 4;
	private static final int DIALOG_EDIT = 5;
	private static final int DIALOG_FILTER = 6;
	private static final int DIALOG_MONITORSIZEMAX = 7;
	private static final int MAINNOTIFIER = 0x1000;
	private static final int ENSUREDISCOVERABLE = 0x1001;
	private static final int REQUEST_ENABLE_BT = 0x2001;
	
    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    
    // Key names received from the BluetoothChatService Handler
    public static final String MESSAGE = "message";
	
	private boolean m_bInSearchView = false;
	private final Timer timer = new Timer();
	
	private IBAMService mBAMService = null;
	private ServiceConnection mServiceConnection = new ServiceConnection() 
	{
        //@Override
        public void onServiceConnected(ComponentName name, IBinder service) 
        {
        	mBAMService = (IBAMService) service;
        	if (mBAMService != null)
        	{
        		mBAMService.setMainOp(BurglarAlarmMonitor.this);
        	}
            Log.i(TAG, "BAMService on serivce connected");
        }

        //@Override
        public void onServiceDisconnected(ComponentName name) 
        {
        	if (mBAMService != null)
        	{
        		mBAMService.setMainOp(null);
        	}
        	mBAMService = null ;
        }
    };
    
    /** Called when the activity is first created. */
    //@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //PackageManager pm = getPackageManager();   
        //ResolveInfo mHomeInfo = pm.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);
        
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        
        String strOpt = dm.widthPixels + "*" + dm.heightPixels;
        Log.i(TAG, strOpt);
        
        metrics = getResources().getDisplayMetrics();
        if (initService()== false)
        {
        	Log.e(TAG, "service init fail.");
        	finish();
        	return;
        }
        
        initValues();
        setContentView(R.layout.main);
        initMain();
        timer.schedule(task, 1000, 1000);       
    }
    
    @Override
    public void onStart() {
        super.onStart();

        makesureBlueboothenable();
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case REQUEST_ENABLE_BT:
            if (resultCode == Activity.RESULT_OK) {  
            	mBAMService.setNeedNotification(); 
            }
            else
            {
            	mBAMService.setNeedNotification(); 
            }
        }
    }
    
    private void initValues()
    {
    	RSSIValue item6 = new RSSIValue();
    	item6.nMaxRSSI = 1000;
    	item6.strDescription = getString(R.string.info_hint); // + getString(R.string.rssi_none);
    	item6.nResId = R.drawable.line0;
    	m_RSSIValues.add(item6);
    	
    	RSSIValue item5 = new RSSIValue();
    	item5.nMaxRSSI = 100;
    	item5.strDescription = getString(R.string.info_hint); // + getString(R.string.rssi_weak);
    	item5.nResId = R.drawable.line1;
    	m_RSSIValues.add(item5);
    	
    	RSSIValue item4 = new RSSIValue();
    	item4.nMaxRSSI = 80;
    	item4.strDescription = getString(R.string.info_hint); // + getString(R.string.rssi_middle);
    	item4.nResId = R.drawable.line2;
    	m_RSSIValues.add(item4);
    	
    	RSSIValue item3 = new RSSIValue();
    	item3.nMaxRSSI = 60;
    	item3.strDescription = getString(R.string.info_hint); //+ getString(R.string.rssi_middle);
    	item3.nResId = R.drawable.line3;
    	m_RSSIValues.add(item3);
    	
    	RSSIValue item2 = new RSSIValue();
    	item2.nMaxRSSI = 50;
    	item2.strDescription = getString(R.string.info_hint); // + getString(R.string.rssi_strong);
    	item2.nResId = R.drawable.line4;
    	m_RSSIValues.add(item2);
    	
    	RSSIValue item1 = new RSSIValue();
    	item1.nMaxRSSI = 40;
    	item1.strDescription = getString(R.string.info_hint); //+ getString(R.string.rssi_strong);
    	item1.nResId = R.drawable.line5;
    	m_RSSIValues.add(item1);
    	
    	RSSIValue item0 = new RSSIValue();
    	item0.nMaxRSSI = 1;
    	item0.strDescription = getString(R.string.info_hint); //+ getString(R.string.rssi_strong);
    	item0.nResId = R.drawable.line5;
    	m_RSSIValues.add(item0);
    }
    
    private RSSIValue getCurRSSIValue(int nRSSI)
    {
    	if(nRSSI == 0)
    	{
    		return m_RSSIValues.get(0);
    	}
    	
    	for (RSSIValue item : m_RSSIValues) 
	    { 
    		if (nRSSI > item.nMaxRSSI)
    			return item;
	    }
    	return m_RSSIValues.get(m_RSSIValues.size() - 1);
    }
    
    private boolean initService()
    {
    	this.startService( new Intent( this , BAMService.class ));
    	return this.bindService( new Intent( "com.yfdice.android.bam.BAMService" ),
                this.mServiceConnection, BIND_AUTO_CREATE);
    }
    
    private void initMain()
    {
    	View newButton = findViewById(R.id.new_button);
        newButton.setOnClickListener(this);
        
        mMonitorlist_up = (FrameLayout)findViewById(R.id.monitorlist_up);
		mMonitorlist_middle = (FrameLayout)findViewById(R.id.monitorlist_middle);
		mMonitorlist_down = (LinearLayout)findViewById(R.id.monitorlist_down);
		mMonitorlist_up.setBackgroundResource(R.drawable.list_bg_up);
		mMonitorlist_middle.setBackgroundResource(R.drawable.list_bg_middle);
		mMonitorlist_down.setBackgroundResource(R.drawable.list_bg_down);
               
        m_listView = (ListView) findViewById(R.id.ListView01); 
                     
        m_listItemAdapter = new ListAdapter(this);
          
        m_listView.setAdapter(m_listItemAdapter);
        m_listView.setCacheColorHint(0); 
               
        m_listView.setOnItemClickListener(new OnItemClickListener() {   
  
            //@Override  
            public void onItemClick(AdapterView<?> arg0, View view, int position,   
                    long id) { 
        		if (false == hasMonitorList())
        			return;
        		
        		mPosition = position;
        		showDialog(DIALOG_OPERATE); 				
            }
        });   
        
        calcListHW();
    }
    
    private void calcListHW()
    {
    	WindowManager windowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
		//int screenWidth = windowManager.getDefaultDisplay().getWidth();
		int screenHight = windowManager.getDefaultDisplay().getHeight();
		final int topGap = 50;
    	final int headerbottomGap = 76;
		final int rowHeight = 58;
    	if (m_bInSearchView)
    	{
    		ViewGroup.LayoutParams layoutParamslist = mSearchlist_middle.getLayoutParams();
    		int cout = m_searchlistAdapter.getCount();
    		
    		if (cout <= 5)
    		{
        		layoutParamslist.height = (int) Math.ceil((5 * rowHeight) * metrics.density);
    		}
    		else
    		{
    			layoutParamslist.height = Math.min((int) Math.ceil((cout * rowHeight) * metrics.density), screenHight - (int) Math.ceil((topGap + headerbottomGap) * metrics.density));
    		}
    		mSearchlist_middle.setLayoutParams(layoutParamslist);
    	}
    	else
		{
    		ViewGroup.LayoutParams layoutParamslist = mMonitorlist_middle.getLayoutParams();
    		int cout = m_listItemAdapter.getCount();
    		if (cout <= 5)
    		{
    			layoutParamslist.height = (int) Math.ceil((5 * rowHeight) * metrics.density);
    		}
    		else
    		{
    			layoutParamslist.height = Math.min((int) Math.ceil((cout * rowHeight) * metrics.density), screenHight - (int) Math.ceil((topGap + headerbottomGap) * metrics.density));
    		}
    		
    		mMonitorlist_middle.setLayoutParams(layoutParamslist);
		}
    	
    }
    
    //@Override
	protected Dialog onCreateDialog(int id){
		switch(id){
			case DIALOG_OPERATE:
			{
				return createOperationDialog();
			}
			case DIALOG_QUIT:
			{
				return createQuitDialog();
			}
			case DIALOG_DELETE:
			{
				return createDeleteDialog();
			}
			case DIALOG_EDIT:
			{
				return createEditDialog();
			}
			case DIALOG_FILTER:
			{
				return createFilterDialog();
			}
			case DIALOG_MONITORSIZEMAX:
			{
				return createMonitorSizeMaxDialog();
			}
		}
		
		return null;
	}
    
    private Dialog createOperationDialog(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);	
		builder.setTitle(R.string.longclick_title);
		
		DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener(){

			//@Override
			public void onClick(DialogInterface dialog, int which) {
				switch(which){
				case 0:
					{
						showDialog(DIALOG_EDIT);
						break;
					}
				case 1:
					{
						showDialog(DIALOG_FILTER);  	 
						break;
						
					}
				case 2:
					{
						showDialog(DIALOG_DELETE);
						break;
					}
				case 3:
					{
						DeviceItem item = mBAMService.getMonitorItem(mPosition).item;
						if (item != null)
						{
							item.strUserName = "";
							mBAMService.updateData(item);
							m_listItemAdapter.notifyDataSetChanged();
						}
						break;
					}
				}
				removeDialog(DIALOG_OPERATE);
			}
		};
		
		DeviceItem item = mBAMService.getMonitorItem(mPosition).item;
   	 	
		if (item != null && item.strUserName != null && item.strUserName.length() > 0)
		{
			String[] menus = {
					getString(R.string.longclick_edit),
					getString(R.string.longclick_monitor),
					getString(R.string.longclick_delete),
					getString(R.string.longclick_reset)
			};
			
			builder.setItems(menus, listener);
		}
		else
		{
			String[] menus = {
					getString(R.string.longclick_edit),
					getString(R.string.longclick_monitor),
					getString(R.string.longclick_delete),
			};
			
			builder.setItems(menus, listener);
		}
		
		return builder.create();
	}
    
    private Dialog createDeleteDialog(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.delete_title);
		builder.setMessage(R.string.delete_message);
		builder.setPositiveButton(R.string.positive_button, new DialogInterface.OnClickListener()
		{
			//@Override
			public void onClick(DialogInterface dialog, int which) {
				DeviceItem item = mBAMService.getMonitorItem(mPosition).item;
				if (item != null)
				{
					item.nFilter = DeviceItem.FilterType_None; // 清空
					mBAMService.removeMonitorItem(mPosition);
					mBAMService.deleteData(item);
					m_listItemAdapter.notifyDataSetChanged();
				}
				removeDialog(DIALOG_DELETE);
			}
			
		});
		
		builder.setNegativeButton(R.string.negative_button, new DialogInterface.OnClickListener()
		{
			//@Override
			public void onClick(DialogInterface dialog, int which) {
				removeDialog(DIALOG_DELETE);
			}
			
		});
		
		return builder.create();
	}
    
    private Dialog createMonitorSizeMaxDialog(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.monitorsizemax_title);
		builder.setMessage(R.string.monitorsizemax_msg);
		builder.setPositiveButton(R.string.positive_button, new DialogInterface.OnClickListener()
		{
			//@Override
			public void onClick(DialogInterface dialog, int which) {
				removeDialog(DIALOG_MONITORSIZEMAX);
			}
			
		});
		
		return builder.create();
	}
    
    private Dialog createEditDialog(){
    	LayoutInflater factory = LayoutInflater.from(this);
    	final View DialogEditView = factory.inflate(R.layout.editinfo, null);
    	
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.edit_title);
		builder.setView(DialogEditView);
		builder.setPositiveButton(R.string.positive_button, new DialogInterface.OnClickListener()
		{
			//@Override
			public void onClick(DialogInterface dialog, int which) {
				DeviceItem item = mBAMService.getMonitorItem(mPosition).item;
				if (item != null)
				{
					EditText editUserName = (EditText)DialogEditView.findViewById(R.id.UsernameEdit);
					item.strUserName = editUserName.getText().toString();
					mBAMService.updateData(item);
					m_listItemAdapter.notifyDataSetChanged();
				}
				removeDialog(DIALOG_EDIT);
			}
			
		});
		
		builder.setNegativeButton(R.string.negative_button, new DialogInterface.OnClickListener()
		{
			//@Override
			public void onClick(DialogInterface dialog, int which) {
				removeDialog(DIALOG_EDIT);
			}
			
		});
		
		return builder.create();
	}
    
    private Dialog createFilterDialog(){
    	LayoutInflater factory = LayoutInflater.from(this);
    	final View DialogEditView = factory.inflate(R.layout.filter, null);
    	
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.longclick_monitor);
		builder.setView(DialogEditView);
		
		RadioGroup radioGroup = (RadioGroup)DialogEditView.findViewById(R.id.RadioGroup);
		final RadioButton radioNone = (RadioButton)DialogEditView.findViewById(R.id.RadioFilterNone);
		final RadioButton radioOnce = (RadioButton)DialogEditView.findViewById(R.id.RadioFilterOnce);
		final RadioButton radioAlways = (RadioButton)DialogEditView.findViewById(R.id.RadioFilterAlways);
	    
	    DeviceItem item = mBAMService.getMonitorItem(mPosition).item;
		if (item != null)
		{
			mFilterType = item.nFilter;
			if (item.nFilter == DeviceItem.FilterType_None)
				radioNone.setChecked(true);
			else if (item.nFilter == DeviceItem.FilterType_Once)
				radioOnce.setChecked(true);
			else
				radioAlways.setChecked(true);
		}

		radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				if (checkedId == radioNone.getId())
				{
					mFilterType = DeviceItem.FilterType_None;
				}
				else if (checkedId == radioOnce.getId())
				{
					mFilterType = DeviceItem.FilterType_Once;
				}
				else
				{
					mFilterType = DeviceItem.FilterType_Always;
				}
			}
		});
		
		builder.setPositiveButton(R.string.positive_button, new DialogInterface.OnClickListener()
		{
			//@Override
			public void onClick(DialogInterface dialog, int which) {
				DeviceItem item = mBAMService.getMonitorItem(mPosition).item;
				if (item != null)
				{
					item.nFilter = mFilterType;
					mBAMService.updateData(item);
					m_listItemAdapter.notifyDataSetChanged();
				}
				removeDialog(DIALOG_FILTER);
			}
			
		});
		
		builder.setNegativeButton(R.string.negative_button, new DialogInterface.OnClickListener()
		{
			//@Override
			public void onClick(DialogInterface dialog, int which) {
				removeDialog(DIALOG_FILTER);
			}
			
		});
		
		return builder.create();
	}
    
    public void onForceQuit()
    {
    	this.stopService( new Intent(BurglarAlarmMonitor.this, BAMService.class ));
    	this.unbindService(mServiceConnection);
		this.finish();
    }
    
    private Dialog createQuitDialog(){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.quit_title);
		builder.setMessage(R.string.quit_message);
		builder.setPositiveButton(R.string.positive_button, new DialogInterface.OnClickListener()
		{
			//@Override
			public void onClick(DialogInterface dialog, int which) {
				onForceQuit();
				removeDialog(DIALOG_QUIT);
			}
			
		});
		
		builder.setNegativeButton(R.string.negative_button, new DialogInterface.OnClickListener()
		{
			//@Override
			public void onClick(DialogInterface dialog, int which) {
				removeDialog(DIALOG_QUIT);
			}
			
		});
		
		return builder.create();
	}
    
    private boolean hasMonitorList()
    {
    	if (mBAMService == null ||  mBAMService.getMonitorCount() <= 0)
    		return false;
    		
    	return true;
    }
    
    public final class ListViewHolder
    {  
    	public TextView title;  
    	public TextView info; 
    	public TextView filter;
    	public CheckBox viewBtn; 
    	public ImageView rssiImg;
    } 

    public class ListAdapter extends BaseAdapter
    {  
        private LayoutInflater mInflater;  

        public ListAdapter(Context context)
        {  
        	this.mInflater = LayoutInflater.from(context);  
        }  

        //@Override 
        public int getCount() 
        {  
        	// TODO Auto-generated method stub
        	if (mBAMService == null)
        		return 1; 
        	
            int nCount = mBAMService.getMonitorCount();  
            if (nCount <= 0)
            	nCount = 1;
            
            return nCount;
        }  
        //@Override 
        public Object getItem(int arg0) 
        {  
            // TODO Auto-generated method stub  
            return null;  
        }  

        //@Override 
        public long getItemId(int arg0) {  
            // TODO Auto-generated method stub  
            return 0;  
        }  

        //@Override 
        public View getView(int position, View convertView, ViewGroup parent) 
        {    	
        	
        	ListViewHolder holder = null;
			if(convertView == null)
			{
				holder = new ListViewHolder();
				convertView = mInflater.inflate(R.layout.list_items, null);
				holder.title = (TextView) convertView.findViewById(R.id.ItemName);
				holder.info = (TextView) convertView.findViewById(R.id.ItemRSSI);
				holder.filter = (TextView) convertView.findViewById(R.id.ItemFilter);
				holder.viewBtn = (CheckBox)convertView.findViewById(R.id.view_checkbox);
				holder.rssiImg = (ImageView) convertView.findViewById(R.id.ItemRSSIImg);
				convertView.setTag(holder);
			}
			else
			{
				holder = (ListViewHolder)convertView.getTag();
			}
			
        	
			if (false == hasMonitorList()) {
				holder.title.setText(R.string.nomonitor_tip);
				ViewGroup.LayoutParams layoutParamslist = holder.title
						.getLayoutParams();
				layoutParamslist.width = metrics.widthPixels;
				holder.title.setLayoutParams(layoutParamslist);
				holder.info.setVisibility(View.GONE);
				holder.filter.setVisibility(View.GONE);
				holder.viewBtn.setVisibility(View.GONE);
				holder.rssiImg.setVisibility(View.GONE);
				convertView.setBackgroundColor(Color.WHITE);
				return convertView;
			}
			else
			{
				holder.info.setVisibility(View.VISIBLE);
				holder.filter.setVisibility(View.VISIBLE);
				holder.viewBtn.setVisibility(View.VISIBLE);
				holder.rssiImg.setVisibility(View.VISIBLE);
			}
			

        	// 内容填充			
			MoniterItem moniterItem = mBAMService.getMonitorItem(position);
			if (moniterItem.item == null)
				return convertView;
			
			// 设置title
			if(moniterItem.item.strUserName != null)
				holder.title.setText(moniterItem.item.strUserName);
			else
				holder.title.setText(moniterItem.item.strName);
			
			
            RSSIValue curRSSIValue = getCurRSSIValue(moniterItem.item.nRSSI);
            String strTmp = curRSSIValue.strDescription + moniterItem.item.nRSSI + 
            				" 电压：" + moniterItem.item.nBattery;
            holder.info.setText(strTmp);
            holder.rssiImg.setImageResource(curRSSIValue.nResId);
			
			if(moniterItem.isOnline() || moniterItem.isLowSingal())
				convertView.setBackgroundColor(Color.WHITE);
			else
				convertView.setBackgroundColor(Color.RED);
			
			if(moniterItem.item.nFilter == DeviceItem.FilterType_Always)
			{
				holder.filter.setText(R.string.ignore_checkbox);
				holder.viewBtn.setChecked(true);
				convertView.setBackgroundColor(Color.WHITE);
			}
			else
			{
				holder.filter.setText(R.string.ignoreonce_checkbox);
				
				if(moniterItem.item.nFilter == DeviceItem.FilterType_None)
					holder.viewBtn.setChecked(false);
				else
				{
					holder.viewBtn.setChecked(true);
					convertView.setBackgroundColor(Color.WHITE);
				}
			}
						
			holder.viewBtn.setTag(position);
            holder.viewBtn.setOnClickListener(new OnClickListener()  
            {  
                //@Override 
            	public void onClick(View v)
                {  
               	 int nPosition = Integer.parseInt(v.getTag().toString()); 
               	 
               	 DeviceItem item = mBAMService.getMonitorItem(nPosition).item;
               	 if (((CheckBox) v).isChecked()) 
               		 item.nFilter = DeviceItem.FilterType_Once;
               	 else
               		 item.nFilter = DeviceItem.FilterType_None;
               	 
               	 mBAMService.updateData(item);
                }  
            } );
			
			return convertView;
        }  

    }  
   
    public final class SearchViewHolder
    {  
    	public TextView title;  
    	public TextView info; 
    	public Button viewBtn;
    	public ImageView rssiImg;
    }  
    public class SearchAdapter extends BaseAdapter
    {  
        private LayoutInflater mInflater;  

        public SearchAdapter(Context context)
        {  
        	this.mInflater = LayoutInflater.from(context);  
        }  

        //@Override 
        public int getCount() 
        {  
        	// TODO Auto-generated method stub 
        	if (mBAMService == null)
        		return 0;
        	
            return mBAMService.getSearchCount();  
        }  
        //@Override 
        public Object getItem(int arg0) 
        {  
            // TODO Auto-generated method stub  
            return null;  
        }  

        //@Override 
        public long getItemId(int arg0) {  
            // TODO Auto-generated method stub  
            return 0;  
        }  

        //@Override 
        public View getView(int position, View convertView, ViewGroup parent) {
        	SearchViewHolder holder = null;  
        	if (convertView == null) 
        	{  
        		holder=new SearchViewHolder();    
        		convertView = mInflater.inflate(R.layout.search_items, null);  
        		holder.title = (TextView)convertView.findViewById(R.id.SearchName);  
        		holder.info = (TextView)convertView.findViewById(R.id.SearchRSSI);  
        		holder.viewBtn = (Button)convertView.findViewById(R.id.view_button);
        		holder.rssiImg = (ImageView)convertView.findViewById(R.id.SearchRSSIImg);
        		//holder.viewBtn.setTag(position);
        		convertView.setTag(holder);  
        	}
        	else 
        	{  
        		holder = (SearchViewHolder)convertView.getTag();  
        	}  
        	
        	DeviceItem item = mBAMService.getSearchItem(position);
        	if (item == null)
        		return convertView;
        	
        	
        	if (item.strUserName != null && item.strUserName.length() > 0)
        		holder.title.setText(item.strUserName);
        	else
        		holder.title.setText(item.strName);  
        	
        	RSSIValue curRSSIValue = getCurRSSIValue(item.nRSSI);
        	String strTmp = curRSSIValue.strDescription + item.nRSSI;
        	holder.info.setText(strTmp);
        	//holder.info.setText(curRSSIValue.strDescription); 
        	holder.rssiImg.setImageResource(curRSSIValue.nResId);
        	holder.viewBtn.setText(R.string.add_button);
        	holder.viewBtn.setTextColor(Color.BLACK);
        	
        	final int nPosition = position;
        	holder.viewBtn.setOnClickListener(new View.OnClickListener() 
        	{  
        		//@Override 
        		public void onClick(View v)
        		{  
        			DeviceItem item = mBAMService.getSearchItem(nPosition);
        			
        			if(item != null)
        			{	
        				boolean bResult = mBAMService.addMonitorItem(item);
        				if (!bResult)
        				{
        					showDialog(DIALOG_MONITORSIZEMAX);
        				}
        			}                
        		}  
        	} ); 
        	
        	return convertView;  
        }  
    }
    
    public void onClick(View v)
    {
    	switch(v.getId())
    	{
    	case R.id.new_button:
    		changeListView(true);
    		//onBluetooth();
    		break;
    	case R.id.return_button:
    		changeListView(false);
    		break;
    	}
    }
    
    void changeListView(boolean bSearch)
    {
    	m_bInSearchView = bSearch;
    	if (bSearch == true)
    	{
			Handler handler = mBAMService.getActivityHandler();	
			if (handler != null)
			{
				Message message = new Message();
				message.what = IBAMService.s_msgEnableBluetooth;
				handler.sendMessage(message);
			}
    		
    		setContentView(R.layout.search_main);
    		View returnButton = findViewById(R.id.return_button);
            returnButton.setOnClickListener(this);
            
            mSearchlist_up = (FrameLayout)findViewById(R.id.searchlist_up);
    		mSearchlist_middle = (FrameLayout)findViewById(R.id.searchlist_middle);
    		mSearchlist_down = (LinearLayout)findViewById(R.id.searchlist_down);
    		mSearchlist_up.setBackgroundResource(R.drawable.list_bg_up);
    		mSearchlist_middle.setBackgroundResource(R.drawable.list_bg_middle);
    		mSearchlist_down.setBackgroundResource(R.drawable.list_bg_down);
    		
            m_searchView = (ListView) findViewById(R.id.ListView02);
            m_searchlistAdapter = new SearchAdapter(this);
            m_searchView.setAdapter(m_searchlistAdapter);
            m_searchView.setCacheColorHint(0); 
            
            calcListHW();
    	}
    	else
    	{
    		setContentView(R.layout.main);
    		initMain();
    		
            if (BluetoothAdapter.getDefaultAdapter().isDiscovering()) {
            	BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
            }
    	}
    }
    
    //@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
    	Log.i(TAG, "BAM Activity destroy.");
		timer.cancel();
//		this.unbindService(mServiceConnection);         
		super.onDestroy();
	}
    
    private TimerTask task = new TimerTask() 
    {
        //@Override
    	public void run() {
    		
    		// TODO Auto-generated method stub
    		Message message = new Message();
    		message.what = BurglarAlarmMonitor.MAINNOTIFIER;
    		m_Mainhandler.sendMessage(message);  			
        }
    };
    
    private Handler m_Mainhandler = new Handler() {
       //@Override
       public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
    	   switch (msg.what) 
           {
               case BurglarAlarmMonitor.MAINNOTIFIER:
            	   Log.i(TAG, "MAINNOTIFIER");
            	   updateViews();
            	   break;
                
               case BurglarAlarmMonitor.ENSUREDISCOVERABLE:
            	   ensureDiscoverableImp();
            	   break;
           }
        super.handleMessage(msg);
       }
    };
    
	private void makesureBlueboothenable()
	{	
		if (BluetoothAdapter.getDefaultAdapter().isEnabled()) 
		{	
			return;
		}
		else
		{		
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            this.startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
		}
	}
    
    private void ensureDiscoverableImp()
    {
        // Get local Bluetooth adapter
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // If the adapter is null, then Bluetooth is not supported
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            return;
        }
        if (bluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    } 
    
    private void updateViews()
    {
    	calcListHW();
    	if (m_bInSearchView)
    	{
    		m_searchlistAdapter.notifyDataSetChanged();
    		ProgressBar precessBar = (ProgressBar) findViewById(R.id.progressBarHorizontal);
    		if (BluetoothAdapter.getDefaultAdapter().isDiscovering())
    		{
    			precessBar.setVisibility(View.VISIBLE);            		   
    		}else
    		{
    			precessBar.setVisibility(View.GONE);            		               		   
    		}
    	}
    	else
    		m_listItemAdapter.notifyDataSetChanged();
    }
    
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {   
        if (keyCode == KeyEvent.KEYCODE_BACK) 
        {   
        	if (m_bInSearchView)
        	{
        		changeListView(false);
        		return true;
        	}
        	else
        	{
        		finish();
        		return true;
        	}
        }
        return super.onKeyDown(keyCode, event);   
    } 
    
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch(item.getItemId())
    	{
    	case R.id.forcequit:
    		showDialog(DIALOG_QUIT);
    		return true;
    	case R.id.about:
    		Intent aboutIn = new Intent(BurglarAlarmMonitor.this, About.class);
    		startActivity(aboutIn);
    		return true;
    	case R.id.settings:
    		Intent settingsIn = new Intent(BurglarAlarmMonitor.this, Settings.class);
    		startActivity(settingsIn);
    		return true;	
    	case R.id.feedback:
    		sendFeedback();
    		return true;
    	}
    	
    	return false;
    }
    
    private void sendFeedback()
    {
    	//系统邮件系统的动作为android.content.Intent.ACTION_SEND
    	Intent email = new Intent(android.content.Intent.ACTION_SEND);
    	email.setType("plain/text");
    	String[] emailReciver = {"victor@firstmetal-cn.com", "hwleung@firstmetal-cn.com"};
    	String[] bccemail={"yfdice@gmail.com"};
    	String emailSubject = getString(R.string.app_name) + getString(R.string.about_version_number) + getString(R.string.feedback_title);
    	//String emailBody = ;

    	//设置邮件默认地址
    	email.putExtra(android.content.Intent.EXTRA_EMAIL, emailReciver);
    	email.putExtra(android.content.Intent.EXTRA_BCC, bccemail);
    	//设置邮件默认标题
    	email.putExtra(android.content.Intent.EXTRA_SUBJECT, emailSubject);
    	//设置要默认发送的内容
    	//email.putExtra(android.content.Intent.EXTRA_TEXT, emailBody);
    	//调用系统的邮件系统
    	startActivity(Intent.createChooser(email, "请选择邮件发送软件"));
    }
}